package com.itheima.filter;


import com.alibaba.fastjson.JSON;
import com.aliyuncs.utils.StringUtils;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class Filters implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化，执行一次");
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求的url
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String url = request.getRequestURI();
        System.out.println("请求的url是：" + url);

        if (url.contains("login")){
            log.info("登录页面，放行");
            filterChain.doFilter(request, response);
            return;
        }

        //判断是否token是否存在
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            //未登录，重定向到登录页面
            Result result = new Result();
            result.setCode(401);
            result.setMessage("请先登录");
            result.setData(null);

            //需要把result对象序列化成json字符串，并设置到response的body中
            //利用fastjson
            String error = JSON.toJSONString(result);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(error);
            return;
        }
        //判断token是否有效
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            //token无效，重定向到登录页面
            Result result = new Result();
            result.setCode(401);
            result.setMessage("请先登录");
            result.setData(null);

            //需要把result对象序列化成json字符串，并设置到response的body中
            //利用fastjson
            String error = JSON.toJSONString(result);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(error);
            return;
        }

        System.out.println("过滤器开始工作");
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("过滤器工作结束");
    }

    @Override
    public void destroy() {
        System.out.println("过滤器销毁,释放资源，执行一次");
        Filter.super.destroy();
    }
}
